package com.simplehc7878.auth.security.jwt;

import com.simplehc7878.auth.security.SecurityConditionOn;
import com.simplehc7878.auth.security.SecurityParams;
import com.simplehc7878.auth.security.ChainConfigure;
import com.simplehc7878.auth.security.SecurityGetter;
import com.simplehc7878.auth.common.Result;
import com.simplehc7878.auth.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.util.AntPathMatcher;

import java.util.Arrays;

@Configuration
@SecurityConditionOn(JwtSecurityConfig.class)
public class JwtSecurityConfig implements SecurityGetter {

    @Value("${jwt.key}")
    private String secret;

    @Bean
    public JwtHelper jwtHelper() {
        return new JwtHelper(secret);
    }

    @Bean
    public AuthenticationEntryPoint customAuthenticationEntryPoint() {
        return (request, response, authException) -> {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType("application/json");
            response.getWriter().write(JsonUtil.toJson(
                    Result.error(HttpStatus.UNAUTHORIZED.value(), authException.getMessage())));
        };
    }

    @Override
    public ChainConfigure getChain() {
        return new JwtChainConfigure();
    }

    @Override
    public SecurityParams getChainParams() {
        SecurityParams params = new SecurityParams();
        params.setOncePerRequestFilter(new JwtAuthTokenFilter(
                jwtHelper(), new AntPathMatcher(), Arrays.asList("/user/auth/**")));
        params.setAuthenticationEntryPoint(customAuthenticationEntryPoint());
        return params;
    }
}
